package com.yongdin.minimalism;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yongdin.minimalism.util.ByteUtil;
import com.yongdin.minimalism.wifi.WifiListActivity;
import com.yongdin.minimalism.wifi.WifiReceiver;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

public class MainActivity extends WeatherActivity {
    //温度
    private TextView tvTemperature;
    //星期
    private TextView tvDayOfWeek;
    //地址
    private TextView tvAddress;
    //低温度
    private TextView tvTemperatureLow;
    //高温度
    private TextView tvTemperatureHigh;
    //日期
    private TextView tvDate;
    //时间
    private TextView tvTime;
    //设备号
    private TextView tvDevice;
    private Banner banner;
    private ArrayList<Integer> images;

    private int week;
    private String year;
    private String month;
    private String day;
    private String weekString;

    private Calendar calendar;
    private String hour;
    private String minute;
    private String second;

    private Handler handler = new Handler();
    private Runnable runnable;
    private WeakReference<TextView> textViewWeakReference;
    private WifiReceiver wifiReceiver;

    private final String PORT_PATH = "/dev/ttyS2";//port
    private final int BAUD_RATE = 115200;//波特率

    // 语音合成对象
    private SpeechSynthesizer mTts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();

        tvTemperature = findViewById(R.id.tv_temperature);
        tvDayOfWeek = findViewById(R.id.tv_day_of_week);
        tvAddress = findViewById(R.id.tv_address);
        tvTemperatureLow = findViewById(R.id.tv_temperature_low);
        tvTemperatureHigh = findViewById(R.id.tv_temperature_high);
        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);
        tvDevice = findViewById(R.id.tv_device);

        banner = (Banner) findViewById(R.id.banner);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                //startActivity(new Intent(StandByActivity.this,KeeperMainActivity.class));
//                finish();
            }
        });
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Stack);
        //设置标题集合（当banner样式有显示title时）
        //banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        //banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();

        textViewWeakReference = new WeakReference(tvDate);
        runnable = new Runnable() {
            @Override
            public void run() {
                if (textViewWeakReference.get() == null) {
                    return;
                }

                getNetTime();
                handler.postDelayed(this, 1000);
            }
        };
        handler.post(runnable);

        ImageView ivWea = findViewById(R.id.iv_wea);
        ivWea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WifiListActivity.class);
                startActivity(intent);
            }
        });
        initWifi();
        initCom();
        SerialPortIOManage.getInstance().connect(PORT_PATH, BAUD_RATE);

        SpeechUtility.createUtility(MainActivity.this, "appid=5e9ab36d");
        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

        setWeatherCallBack(new WeatherCallBack() {
            @Override
            public void callBack(String city, Cast cast) {
                tvTemperatureHigh.setText(cast.daytemp + "°");
                tvTemperatureLow.setText(cast.nighttemp + "°");
                try {
                    tvAddress.setText(city.substring(0, city.length() - 1));
                } catch (Exception e) {

                }
            }
        });
    }

    private boolean isPlay;
    private boolean playEnable;

    private void play() {
        if (isPlay && playEnable) {
            return;
        }
        int code = mTts.startSpeaking("今日温度" + tvTemperature.getText().toString(), new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
                isPlay = true;
            }

            @Override
            public void onBufferProgress(int i, int i1, int i2, String s) {

            }

            @Override
            public void onSpeakPaused() {

            }

            @Override
            public void onSpeakResumed() {

            }

            @Override
            public void onSpeakProgress(int i, int i1, int i2) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                isPlay = false;
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("aaa", "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(MainActivity.this, "初始化失败,错误码：" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案", Toast.LENGTH_SHORT).show();
            } else {
                Log.d("aaa", "success" + code);
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        if (null != wifiReceiver) {
            unregisterReceiver(wifiReceiver);
        }
    }

    private void initData() {
        images = new ArrayList<>();
        images.add(R.drawable.banner_two);
        images.add(R.drawable.banner_xx);
        images.add(R.drawable.banner_three);
    }

    private void getNetTime() {
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        week = calendar.get(Calendar.DAY_OF_WEEK);
        year = String.valueOf(calendar.get(Calendar.YEAR));
        month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        day = String.valueOf(calendar.get(Calendar.DATE));
        if (calendar.get(Calendar.AM_PM) == 0) {
            hour = String.valueOf(calendar.get(Calendar.HOUR));
        } else {
            hour = String.valueOf(calendar.get(Calendar.HOUR) + 12);
        }
        minute = String.valueOf(calendar.get(Calendar.MINUTE));
        if (minute.length() == 1) {
            minute = "0" + minute;
        }
        second = String.valueOf(calendar.get(Calendar.SECOND));
        if (week == 1) {
            weekString = "Sun";
        } else if (week == 2) {
            weekString = "Mon";
        } else if (week == 3) {
            weekString = "Tues";
        } else if (week == 4) {
            weekString = "Wed";
        } else if (week == 5) {
            weekString = "Thur";
        } else if (week == 6) {
            weekString = "Fri";
        } else if (week == 7) {
            weekString = "Sat";
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //tv_time.setText(format);
                tvTime.setText(hour + " :" + minute);

                tvDate.setText(year + "  ·  " + month + "  ·  " + day);
                tvDayOfWeek.setText(weekString);

            }
        });

        SerialPortIOManage.getInstance().sendbytes(ByteUtil.hex2bytes("AA0600000F000000000000A3"));
    }

    private void initCom() {
        SerialPortIOManage.getInstance().setonSerialPortIOListener(new SerialPortIOManage.onSerialPortIOListener() {
            @Override
            public void OnConnectStatusCallBack(boolean statue) {

            }

            @Override
            public void OnIOCallBack(int which, final byte[] bytes, int length) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (12 == bytes.length && bytes[0] == (byte) 0xAA && bytes[1] == 0x06 && bytes[4] == 0x00) {
                            double temp = ByteUtil.bytetoInt(bytes[9], bytes[10]) / 10.0;
                            tvTemperature.setText((int) temp + "°");
                        }
                        if (bytes[0] == (byte) 0xAA && bytes[1] == 0x06 && bytes[4] == 0x07) {
                            if (bytes[5] == 0x02) {
                                play();
                            }
                        }
                    }
                });

            }
        });

    }

    public void enablePlay(View view) {
        playEnable = !playEnable;
        ImageView imageView = (ImageView) view;
        if (playEnable) {
            imageView.setImageResource(R.drawable.ico_user_enable);
        } else {
            imageView.setImageResource(R.drawable.ico_user);
        }
    }

    /**
     * 网络加载图片
     * 使用了Glide图片加载框架
     */
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context)
                    .load((Integer) path)
                    .into(imageView);
        }
    }

    private void initWifi() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        AndPermission.with(this).runtime().permission(new String[]{Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION})
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        if (!wifiManager.isWifiEnabled()) {
//                            tvWifiState.setText("WiFi已关闭");
                        } else {
                            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                            if (null == wifiInfo) {
                                Toast.makeText(MainActivity.this, "WiFi未连接", Toast.LENGTH_SHORT).show();
//                                tvWifiState.setText("WiFi未连接");
                            } else {
                                Toast.makeText(MainActivity.this, "WiFi已连接", Toast.LENGTH_SHORT).show();
//                                tvWifiState.setText("WiFi已连接：" + wifiInfo.getSSID());
//                                tvIp.setText("IP: " + Utils.intToIp(wifiInfo.getIpAddress()));
                            }
                        }
                        IntentFilter filter = new IntentFilter();
                        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                        wifiReceiver = new WifiReceiver(new WifiReceiver.IWifiCallBack() {
                            @Override
                            public void onDisconnect() {
//                                tvWifiState.setText("WiFI未连接");
                                Toast.makeText(MainActivity.this, "WiFI未连接", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onConnected(String ssid, String ip) {
//                                tvWifiState.setText("WiFi已连接：" + ssid);
//                                tvIp.setText("IP: " + ip);
                                Toast.makeText(MainActivity.this, "WiFi已连接", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onClosed() {
//                                tvWifiState.setText("WiFi已关闭");
                            }
                        });
                        registerReceiver(wifiReceiver, filter);
                    }
                }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                Toast.makeText(MainActivity.this, "请授予定位权限", Toast.LENGTH_LONG).show();
            }
        }).start();

    }

}
